package com.cskaoyan.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.BaseBusinessException;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {
    @Autowired
    StockMapper stockMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    /**
     * 2.锁定库存
     *
     * @param context
     * @return boolean
     * @author lwq
     * @since 2022/12/03 11:23
     */
    @Override
    @Transactional
    public boolean handle(TransHandlerContext context) {
        CreateOrderContext createOrderContext = (CreateOrderContext) context;
        List<Long> buyProductIds = createOrderContext.getBuyProductIds();
        List<Stock> stockList = stockMapper.findStocksForUpdate(buyProductIds);
        if (CollectionUtils.isEmpty(stockList)) {
            throw new BizException(OrderRetCode.ALL_PRODUCTS_STOCK_NOT_INIT.getCode(), OrderRetCode.ALL_PRODUCTS_STOCK_NOT_INIT.getMessage());
        }
        if (stockList.size() != buyProductIds.size()) {
            throw new BizException(OrderRetCode.PART_OF_PRODUCTS_STOCK_NOT_INIT.getCode(), OrderRetCode.PART_OF_PRODUCTS_STOCK_NOT_INIT.getMessage());
        }
        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        // 锁定库存
        // TODO 判断是否超出限购数量
        for (CartProductDto cartProductDto : cartProductDtoList) {
            Stock stock = new Stock();
            stock.setItemId(cartProductDto.getProductId());
            stock.setLockCount(cartProductDto.getProductNum().intValue());
            stock.setStockCount(-cartProductDto.getProductNum());
            int i = stockMapper.updateStock(stock);
            if (i != 1) {
                throw new BizException(OrderRetCode.DB_SAVE_EXCEPTION.getCode(), OrderRetCode.DB_SAVE_EXCEPTION.getMessage());
            }
        }
        return true;
    }
}